package com.wit.dao.impl;

import hibernate.HibernateSessionFactory;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.wit.po.Company;
import com.wit.po.Mark;
import com.wit.dao.MarkDao;

public class MarkDaoImpl implements MarkDao {

	
	public boolean addMark(Mark mark) {
		Session s = null;
		Transaction tx = null;
		boolean isFinished = false;
		try{
			s = HibernateSessionFactory.getSession();
			tx =  s.beginTransaction();
			s.save(mark);
			tx.commit();
			s.close();
			isFinished = true;
		}catch(HibernateException e){
			tx.rollback();
			e.printStackTrace();
		}finally{
			if(s.isOpen())
				s.close();
		}
		return isFinished;
	}

	
	public boolean deleteMark(Mark mark) {
		Session s = null;
		Transaction tx = null;
		boolean isFinished = false;
		try{
			s = HibernateSessionFactory.getSession();
			tx =  s.beginTransaction();
			s.delete(mark);
			tx.commit();
			s.close();
			isFinished = true;
		}catch(HibernateException e){
			tx.rollback();
			e.printStackTrace();
		}finally{
			if(s.isOpen())
				s.close();
		}
		return isFinished;
	}

	
	public List<Mark> findAllMark() {
		List<Mark> markList = new ArrayList<Mark>();
		try{
			markList = (List<Mark>)HibernateSessionFactory.getSession().createQuery("FROM Mark").list();
		}catch(HibernateException e){
			e.printStackTrace();
		}
		return markList;
	}

	
	public boolean modifyMark(Mark mark) {
		Session s = null;
		Transaction tx = null;
		boolean isFinished = false;
		try{
			s = HibernateSessionFactory.getSession();
			tx =  s.beginTransaction();
			s.update(mark);
			tx.commit();
			s.close();
			isFinished = true;
		}catch(HibernateException e){
			tx.rollback();
			e.printStackTrace();
		}finally{
			if(s.isOpen())
				s.close();
		}
		return isFinished;
	}

	
	public Mark findByIdentifier(String markId) {
		List<Mark> markList = new ArrayList<Mark>();
		try{
			markList = (List<Mark>)HibernateSessionFactory.getSession().createQuery("FROM Mark WHERE markId=?").setString(0, markId).list();
		}catch(HibernateException e){
			e.printStackTrace();
		}
		if(markList.size() == 1)
			return markList.get(0);
		else
			return null;
	}

}
